rust에서 문자열은 compound type이다.
from()
and into()
come from the From
and Into
traits respectively: they are for losslessly converting between arbitrary types, not just strings.
Into
is automatically implemented if you implement the From
trait, so normally (unless coherence rules prevent it) you would only ever implement the From
trait.
to_string
comes from the ToString
trait. This trait is automatically implemented for all types which implement the Display
trait. You would never implement ToString
directly. In this case the reason for two traits is that Display
is the more fundamental one, it's more powerful and more efficient because it doesn't require allocating a String
. However ToString
can be more convenient to use for the caller.
let s = "String"; // type &str , .to_string()으로 변경 가능
let ss = String::from("String!"); // type std::string::String
문자열 합치기
let h = String::from("Hello ");
let w = String::from("World!");
let s = h + &w // concat(self, &String) h -> s, ownership
println!("{}", s);
8개 정도 문자열
// owned type
// String 가변형 속성에 사용할 때 편리함. 자기 데이터를 갖고있는
let my_name = "David".to_string() // String
let other_name = Srting::from("David2");
// growable + shrinkable
let mut my_other_name = "David3".to_string();
my_other_name.push('!');
// &str "string slice"
fn main() {
//String
//.capacity
//.push 이건 캐릭터
//.push_str 이건 문자열
//.pop
// with_capacity allocation
//.len
let mut my_name = "David".to_string();
my_name.push('!');
println!("My name is {}", my_name);
let mut aa = String::with_capacity(26); // 바이트 할당 reallocation 없음
}
export const _frontmatter = {"title":"Rust - string","author":"vlwkaos","tags":[],"aliases":[],"created":"2022-02-06:14:53:38"}